package com.tsp_tux.demo.Service;

import com.tsp_tux.demo.Dao.ArticleRepository;
import com.tsp_tux.demo.Dao.Article_UserRepository;
import com.tsp_tux.demo.Dao.Article_User_PraiseRepository;
import com.tsp_tux.demo.Dao.UserRepository;
import com.tsp_tux.demo.Entity.*;
import com.tsp_tux.demo.Enum.PictureType;
import com.tsp_tux.demo.Mapper.UserDao;
import com.tsp_tux.demo.Mapper.UserMapper;
import com.tsp_tux.demo.Util.QiNiuPicture;
import com.tsp_tux.demo.Util.SHA;
import com.tsp_tux.demo.Util.SendEmail;
import com.tsp_tux.demo.Util.easyRespBean;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张帅 童一凡
 */
@Service
public class UserServiceImp implements UserService {
    @Resource
    private  UserDao userDao;
    @Resource
    private UserMapper userMapper;
    @Resource
    UserRepository userRepository;
    @Resource
    SendEmail sendEmail;

    public User SearchUserName(String name) {
        return (userDao.SearchUserName(name));
    }

    public List<User> SearchUserNamemohu(String name) {
        return (userDao.SearchUserNamemohu(name));
    }

    @Override
    public List<UserHead_List> getHead(String uid) {
        return userMapper.getHead(uid);
    }

    public List<User> SearchUserID(String uid) {
        return userDao.SearchUserID(uid);
    }

    /**
     * 修改头像
     * @author 张志豪
     */
    @Override
    public RespBean changeIcon(String uid, MultipartFile iconFile) {
        if (iconFile.isEmpty()) {
            return new RespBean(500, "请选择文件", null);
        }
        //文件大于10MB，重传
        if (iconFile.getSize() > 10 * 1024 * 1024){
            return new RespBean(500,"图片文件过大，请重新上传",null);
        }
        String fileName ;
        String iconType=iconFile.getContentType();
        String fileSuffix;
        if (iconType!=null&&iconType.contains("image")) {
            fileSuffix = iconType.replace("image/", "");
        }else {
            return new RespBean(500,"格式不正确",null);
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String key;

        System.out.println("收到修改头像请求，uid:"+uid+"  文件类型:"+fileSuffix+" 图片文件大小:"
                +String.format("%.3f",iconFile.getSize()/1048576.00)+"MB");
        //如果是图片则上传到七牛云并形成外链
        if (PictureType.isInclude(fileSuffix)) {
            byte[] uploadBytes;
            Map<String, String> map = new HashMap<>();
            //如果文件大小超过5M进行压缩
            if (iconFile.getSize() > 5 * 1024 * 1024) {
                try {
                    Thumbnails.of(iconFile.getInputStream())
                            .scale(1f)
                            .outputQuality(0.5f)
                            .outputFormat("jpeg")
                            .toOutputStream(outputStream);
                    uploadBytes = outputStream.toByteArray();
                    fileName = SHA.SHA256(outputStream);
                    map = QiNiuPicture.upload(fileName, uploadBytes);
                } catch (IOException | NoSuchAlgorithmException e) {
                    System.out.println("图片压缩或上传时发生错误");
                }
            } else {
                try {
                    uploadBytes = iconFile.getBytes();
                    outputStream.write(uploadBytes);
                    fileName = SHA.SHA256(outputStream);
                    map = QiNiuPicture.upload(fileName, uploadBytes);
                } catch (IOException | NoSuchAlgorithmException e) {
                    System.out.println("头像大小无需压缩，上传时出现错误");
                }
            }
            try{
                outputStream.reset();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (map.containsKey("key")) {
                key = map.get("key");
                String outerChain = QiNiuPicture.outerChainBuild(key);
                if (outerChain == null) {
                    return easyRespBean.err();
                }
                User user=userRepository.findById(uid).get();
                user.setIconurl(outerChain);
                userRepository.save(user);
                System.out.println(uid+"头像图片外链: "+outerChain);
                return new RespBean(200,"头像修改成功!",outerChain);
            }
            return new RespBean(500,"上传失败!",null);
        } else {
            return new RespBean(500, "上传的不是图片类型", null);
        }
    }

    /**
     * 校验验证码(包括时间有效性)
     * @author 张志豪
     */
    @Override
    public int checkVerifyCode(String inputCode, HttpSession session) {
        //有效期验证
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime sendTime = LocalDateTime.parse((String) session.getAttribute("sendTime"), formatter);
        LocalDateTime reciveTime = LocalDateTime.parse(dateTime.format(formatter), formatter);
        long min = ChronoUnit.MINUTES.between(sendTime, reciveTime);
        if (min > 10 || min < 0) {
            return 1;
        }
        //验证码检验
        String verifyCode = (String) session.getAttribute("verifyCode");

        if (inputCode.equals(verifyCode)){
            return 0;
        }else {
            return 2;
        }
    }

    /**
     * 修改邮箱
     * @author 张志豪
     */
    @Override
    public RespBean changeEmail(String uid, String email) {
        try {
            User user = userRepository.findById(uid).get();
            user.setEmail(email);
            userRepository.save(user);
            return easyRespBean.okWithMsg( "邮箱修改成功！");
        } catch (Exception e) {
            return easyRespBean.okWithMsg("邮箱修改失败！");
        }
    }

    /**
     *发送邮箱操作验证码
     * @author 张志豪
     */
    @Override
    @Async
    public void sendChangeEmailVerifyCode(String uid, String email,String verifyCode) {
        Map<String, String> map=new HashMap<>();
        map.put("mailto",email);
        map.put("subject","知识汇聚平台_修改邮箱验证码");
        map.put("content","您好，您的账号:"+uid+" 正在进行修改邮箱操作，此次操作的验证码为：<strong>"+verifyCode+"</strong><br>" +
                "请妥善保管，验证码10分钟内有效。<br><br>" +
                "如果不是您本人进行操作，请无视本邮件<br>" +
                "（本邮件自动发送，请勿回复）");

        sendEmail.sendEmail(map);
    }
}
